package simu

import (
	"fmt"
	"topobuild/utils"

	"github.com/xuri/excelize/v2"
)

/*
rsing_id	dev_id	dev_ip	dev_name	city	province	dev_type
1	1	100.10.0.1	device-a	北京	北京	核心节点
1	2	100.10.0.2	device-b	北京	北京	一般节点
1	3	100.10.0.3	device-c	北京	北京	一般节点
*/

type TableDevice struct {
	RsingId  int    `json:"rsing_id"`
	DevId    int    `json:"dev_id"`
	DevIp    string `json:"dev_ip"`
	DevName  string `json:"dev_name"`
	City     string `json:"city"`
	Province string `json:"province"`
	DevType  string `json:"dev_type"`
}

// 将TableDevice中的数据,写入到指定xlsx文件的dev表中
func WriteDevXlsx(filename string, devs []TableDevice) {
	// 如果filename已经存在,则直接打开,否则创建一个新文件
	utils.CheckFile(filename)
	xlsx, err := excelize.OpenFile(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer xlsx.Close()
	// Create a new sheet.
	index, err := xlsx.NewSheet("device")
	if err != nil {
		fmt.Println(err)
		return
	}
	// Set value of a cell.
	xlsx.SetCellValue("device", "A1", "rsing_id")
	xlsx.SetCellValue("device", "B1", "dev_id")
	xlsx.SetCellValue("device", "C1", "dev_ip")
	xlsx.SetCellValue("device", "D1", "dev_name")
	xlsx.SetCellValue("device", "E1", "city")
	xlsx.SetCellValue("device", "F1", "province")
	xlsx.SetCellValue("device", "G1", "dev_type")
	// 设置单元格样式
	// style, _ := xlsx.NewStyle(`{"alignment":{"horizontal":"center"}}`)
	// xlsx.SetCellStyle("dev", "A1", "G1", style)
	// 设置列宽
	// xlsx.SetColWidth("dev", "A", "G", 20)
	// 设置行高
	// Set active sheet of the workbook.
	xlsx.SetActiveSheet(index)
	// Save xlsx file by the given path.
	fmt.Printf("len(devs): %v\n", len(devs))
	for i, dev := range devs {
		xlsx.SetCellValue("device", fmt.Sprintf("A%d", i+2), dev.RsingId)
		xlsx.SetCellValue("device", fmt.Sprintf("B%d", i+2), dev.DevId)
		xlsx.SetCellValue("device", fmt.Sprintf("C%d", i+2), dev.DevIp)
		xlsx.SetCellValue("device", fmt.Sprintf("D%d", i+2), dev.DevName)
		xlsx.SetCellValue("device", fmt.Sprintf("E%d", i+2), dev.City)
		xlsx.SetCellValue("device", fmt.Sprintf("F%d", i+2), dev.Province)
		xlsx.SetCellValue("device", fmt.Sprintf("G%d", i+2), dev.DevType)
	}
	err = xlsx.SaveAs(filename)
	if err != nil {
		fmt.Println(err)
	}
}
